package whitefox.gqtcard.dblocation;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBLocation {
	private SQLiteDatabase database = null;
	private Activity context;

	public DBLocation() {
		super();
	}

	public DBLocation(Activity context) {
		this.setContext(context);

		DBConfig config = new DBConfig("mylocation.db", context);
		database = config.getdatabase();

	}

	public ArrayList<Location> findall() {
		ArrayList<Location> list = new ArrayList<Location>();

		Cursor c = null;
		try {
			database.query("mylocation", null, null, null, null, null, null);
		} catch (Exception e) {
			String sql = "CREATE TABLE mylocation (";
			sql += "id TEXT PRIMARY KEY,";
			sql += "name TEXT,";
			sql += "note TEXT,";
			sql += "latitude DOUBLE,";
			sql += "longitude DOUBLE)";
			database.execSQL(sql);
		}
		c = database.query("mylocation", null, null, null, null, null, null);
		c.moveToFirst();
		while (c.isAfterLast() == false) {
			Location location = new Location(null, null, null, 0, 0);
			location.setM_ID_Location(c.getString(0));
			location.setM_Name_Location(c.getString(1));
			location.setM_Note_Location(c.getString(2));
			location.setM_latitude(c.getDouble(3));
			location.setM_longitude(c.getDouble(4));
			list.add(location);
			c.moveToNext();
		}
		c.close();
		return list;

	}

	public boolean createLocation(Location location) {
		ContentValues values = new ContentValues();
		values.put("id", location.getM_ID_Location());
		values.put("name", location.getM_Name_Location());
		values.put("note", location.getM_Note_Location());
		values.put("latitude", location.getM_latitude());
		values.put("longitude", location.getM_longitude());
		if (database.insert("mylocation", null, values) == -1) {
			return false;
		} else
			return true;
	}

	public boolean remoteLocation(String id) {
		if (database.delete("mylocation", "id=" + id, null) == -1) {
			return false;
		}
		return true;
	}

	public double latitude(Location location){
		return location.m_latitude;
	}
	
	public double Longitude(Location location){
		return location.m_longitude;
	}
	
	public boolean updateLocation(Location location) {
		ContentValues values = new ContentValues();
		values.put("id", location.getM_ID_Location());
		values.put("name", location.getM_Name_Location());
		values.put("note", location.getM_Note_Location());
		values.put("latitude", location.getM_latitude());
		values.put("longitude", location.getM_longitude());
		if (database.update("mylocation", values,
				"id = " + location.getM_ID_Location(), null) == -1) {
			return false;
		} else
			return true;
	}

	public Activity getContext() {
		return context;
	}

	public void setContext(Activity context) {
		this.context = context;
	}
}
